package com.lsl.test1;

/**
 * @author lishuailong
 * @create 2020-07-06 16:20
 */
public class 生产者消费者问题 {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Productor productor = new Productor(clerk);
        Custoner custoner = new Custoner(clerk);
        Custoner custoner1 = new Custoner(clerk);


        productor.start();
        custoner.start();
        custoner1.start();
    }
}

/**
 * 店员
 */
class Clerk{
    private int productNum=0;

    public Clerk() {
    }

    /**
     * 生产产品
     */
    public synchronized void production() {
        if (productNum<20){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            productNum++;
            System.out.println("生产者生产了，第"+productNum+"个产品！");
            this.notify();
        }else {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 消费产品
     */
    public synchronized void consumption() {
        if (productNum>0){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("消费者消费了，第"+productNum+"个产品！");
            productNum--;
            this.notify();
        }else {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
/**
 * 生产者
 */
class Productor extends Thread{
    private Clerk clerk;

    public Productor(Clerk clerk) {
        this.clerk = clerk;
    }
    @Override
    public void run() {
        while (true){
            clerk.production();
        }
    }
}
/**
 * 消费者
 */
class Custoner extends Thread{
    private Clerk clerk;

    public Custoner(Clerk clerk) {
        this.clerk = clerk;
    }
    @Override
    public void run() {
        while (true){
            clerk.consumption();
        }
    }
}
